import { FormTypes } from '@/utils/JEditableTableUtil'
import {
  findBySelectCus,
  findBySelectRetail,
  findBySelectSup,
  findKucunAll,
  findShipuAll,
  findShipuDayAll,
  getCurrentSystemConfig,
  getPersonByNumType,
  getShipuList
} from '@/api/api'
import { getAction } from '@/api/manage'
import { getCheckFlag, getFormatDate } from '@/utils/util'
import { USER_INFO } from '@/store/mutation-types'
import Vue from 'vue'

export const BillModalMixin = {
  data() {
    return {
      action: '',
      manyAccountBtnStatus: false,
      supList: [],
      cusList: [],
      retailList: [],
      personList: {
        options: [],
        value: ''
      },
      currentSelectDepotId: '',
      depotList: [],
      accountList: [],
      accountIdList: [],
      accountMoneyList: [],
      billUnitPirce: '',
      scanBarCode: '',
      scanStatus: true,
      billStatus: '0',
      minWidth: 1100,
      isCanCheck: true,
      isTenant: false,
      /* 原始审核是否开启 */
      checkFlag: true,
      validatorRules:{
        price:{
          rules: [
            { pattern: /^(([0-9][0-9]*)|([0]\.\d{0,4}|[0-9][0-9]*\.\d{0,4}))$/, message: '金额格式不正确!' }
          ]
        }
      },
      spans: {
        labelCol1: {span: 2},
        wrapperCol1: {span: 22},
        //1_5: 分为1.5列（相当于占了2/3）
        labelCol1_5: { span: 3 },
        wrapperCol1_5: { span: 21 },
        labelCol2: {span: 4},
        wrapperCol2: {span: 20},
        labelCol3: {span: 6},
        wrapperCol3: {span: 18},
        labelCol6: {span: 12},
        wrapperCol6: {span: 12}
      },
    };
  },
  created () {
    let userInfo = Vue.ls.get(USER_INFO)
    this.isTenant = userInfo.id === userInfo.tenantId? true:false
    let realScreenWidth = window.screen.width
    this.width = realScreenWidth<1500?'1200px':'1550px'
    this.minWidth = realScreenWidth<1500?1150:1500
  },
  computed: {
    readOnly: function() {
      return this.action !== "add" && this.action !== "edit";
    }
  },
  methods: {
    addInit(amountNum) {
      this.$nextTick(() => {
        this.form.setFieldsValue({'operTime':getFormatDate()})
      })
      this.accountIdList = []
      this.accountMoneyList = []
      this.manyAccountBtnStatus = false
    },
    addInitWeek() {
      this.$nextTick(() => {
        this.form.setFieldsValue({'startDate':getFormatDate()})
      })
    },
    copyAddInit(amountNum) {
      this.$nextTick(() => {
        this.form.setFieldsValue({'operTime':getFormatDate()})
      })
    },
    /** 查询某个tab的数据 */
    requestSubTableData(url, params, tab, success) {
      tab.loading = true
      getAction(url, params).then(res => {
        console.log(res)
        if(res && res.code === 200){
          tab.dataSource = res.data
          let newDetailArr = []
          for (let i = 0; i < res.data.length; i++) {
            let detail = {}
            detail.type = res.data[i].type
            detail.shipu = res.data[i].name
            detail.kucun = res.data[i].shicai
            detail.amount = res.data[i].shicaiAmount
            newDetailArr.push(detail)
          }
          this.materialTable.dataSource = newDetailArr
          typeof success === 'function' ? success(res) : ''
        }
      }).finally(() => {
        tab.loading = false
      })
    },
    /** 查询某个tab的数据 */
    requestSubTableDataWeek(url, params, tab, success) {
      tab.loading = true
      getAction(url, params).then(res => {
        if(res && res.code == 200){
          tab.dataSource = res.data
          let newDetailArr = []
          for (let i = 0; i < res.data.length; i++) {
            let detail = {}
            detail.day = res.data[i].day
            detail.week = res.data[i].week
            detail.lunch = res.data[i].lunch
            detail.dinner = res.data[i].dinner
            detail.night = res.data[i].night
            detail.remark = res.data[i].remark
            newDetailArr.push(detail)
          }
          this.materialTable.dataSource = newDetailArr
          console.log(this.materialTable)
          typeof success === 'function' ? success(res) : ''
        }
      }).finally(() => {
        tab.loading = false
      })
    },
    //改变字段的状态，1-显示 0-隐藏
    changeFormTypes(columns, key, type) {
      for(let i=0; i<columns.length; i++){
        if(columns[i].key === key) {
          if(type){
            if(key === 'snList' || key === 'batchNumber') {
              if(this.prefixNo === 'LSCK' || this.prefixNo === 'CGTH'  || this.prefixNo === 'XSCK' || this.prefixNo === 'QTCK' || this.prefixNo === 'DBCK') {
                columns[i].type = FormTypes.popupJsh //显示
              } else {
                if(key === 'snList') {
                  columns[i].type = FormTypes.popupJsh //显示
                } else {
                  columns[i].type = FormTypes.input //显示
                }
              }
            } else if(key === 'expirationDate') {
              if(this.prefixNo === 'LSTH' || this.prefixNo === 'CGRK' || this.prefixNo === 'XSTH' || this.prefixNo === 'QTRK') {
                columns[i].type = FormTypes.date //显示
              } else {
                columns[i].type = FormTypes.input //显示
              }
            } else {
              columns[i].type = FormTypes.normal //显示
            }
          } else {
            columns[i].type = FormTypes.hidden //隐藏
          }
        }
      }
    },
    initSystemConfig() {
      getCurrentSystemConfig().then((res) => {
        if(res.code === 200 && res.data){
          let multiBillType = res.data.multiBillType
          let multiLevelApprovalFlag = res.data.multiLevelApprovalFlag
          this.checkFlag = getCheckFlag(multiBillType, multiLevelApprovalFlag, this.prefixNo)
          this.purchaseBySaleFlag = res.data.purchaseBySaleFlag==='1'?true:false
          this.inOutManageFlag = res.data.inOutManageFlag==='1'?true:false
        }
      })
    },
    initSupplier() {
      let that = this;
      findBySelectSup({}).then((res)=>{
        if(res) {
          that.supList = res;
        }
      });
    },
    initCustomer() {
      let that = this;
      findBySelectCus({}).then((res)=>{
        if(res) {
          that.cusList = res;
        }
      });
    },
    initRetail() {
      let that = this;
      findBySelectRetail({}).then((res)=>{
        if(res) {
          that.retailList = res;
        }
      });
    },
    initSalesman() {
      let that = this;
      getPersonByNumType({type:1}).then((res)=>{
        if(res) {
          that.personList.options = res;
        }
      });
    },
    initShipu() {
      let that = this;
      findShipuAll({}).then((res)=>{
        if(res && res.code === 200) {
          let arr = res.data
          for(let item of that.materialTable.columns){
            if(item.key == 'shipu') {
              item.options = []
              for(let i=0; i<arr.length; i++) {
                let displayName = arr[i].type + ' _ ' + arr[i].name
                let depotInfo = {};
                depotInfo.value = displayName //注意-此处value必须为字符串格式
                depotInfo.text = displayName
                depotInfo.title = displayName
                item.options.push(depotInfo)
              }
            }
          }
        }
      })
    },
    initShipuDay() {
      let that = this;
      findShipuDayAll({}).then((res)=>{
        if(res && res.code === 200) {
          let arr = res.data
          for(let item of that.materialTable.columns){
            if(item.key == 'day') {
              item.options = []
              for(let i=0; i<arr.length; i++) {
                let day = arr[i].day
                let depotInfo = {};
                depotInfo.value = day
                depotInfo.text = day
                depotInfo.title = day
                item.options.push(depotInfo)
              }
            }
          }
        }
      })
    },
    initKucun() {
      let that = this;
      findKucunAll({}).then((res)=>{
        if(res && res.code === 200) {
          let arr = res.data
          for(let item of that.materialTable.columns){
            if(item.key == 'kucun') {
              item.options = []
              for(let i=0; i<arr.length; i++) {
                let depotInfo = {};
                depotInfo.value = arr[i].name + '' //注意-此处value必须为字符串格式
                depotInfo.text = arr[i].name
                depotInfo.title = arr[i].name
                depotInfo.amount = arr[i].amount
                item.options.push(depotInfo)
              }
            }
          }
        }
      })
    },
    initWeek() {
      let that = this;
      let arr = ['星期一','星期二','星期三','星期四','星期五','星期六','星期日']
      for(let item of that.materialTable.columns) {
        if (item.key == 'week') {
          item.options = []
          for (let i = 0; i < arr.length; i++) {
            let week = arr[i]
            let depotInfo = {};
            depotInfo.value = week
            depotInfo.text = week
            depotInfo.title = week
            item.options.push(depotInfo)
          }
        }
      }
    },
    onAdded(event) {
      const { row, target } = event
      target.setValues([{rowKey: row.id, values: {amount:0}}])
      if(this.currentSelectDepotId) {
        //如果单据选择过仓库，则直接从当前选择的仓库加载
        target.setValues([{rowKey: row.id, values: {depotId: this.currentSelectDepotId}}])
      } else {
        getAction('/depot/findDepotByCurrentUser').then((res) => {
          if (res.code === 200) {
            let arr = res.data
            if(arr.length===1) {
              target.setValues([{rowKey: row.id, values: {depotId: arr[0].id+''}}])
            } else {
              for (let i = 0; i < arr.length; i++) {
                if(arr[i].isDefault){
                  target.setValues([{rowKey: row.id, values: {depotId: arr[i].id+''}}])
                }
              }
            }
          }
        })
      }
    },
    //单元值改变一个字符就触发一次
    onValueChange(event) {
      let that = this
      const { type, row, column, value, target } = event
      let param,amount
      switch(column.key) {
        case "kucun":
          column.options.forEach(option => {
            if(option.value == value){
              let kucunAmount = 0
              if(option.amount){
                kucunAmount = option.amount
              }
              that.autoChangeKucunAmount(kucunAmount)

              target.setValues([{rowKey: row.id, values: {kucunAmount: kucunAmount, kucunAmountResult: kucunAmount}}])
              target.recalcAllStatisticsColumns()
            }
          })
          break;
        case "day":
          if(row.day){
            getShipuList({'day': row.day}).then((res)=>{
              if(res && res.code === 200) {
                let arr = res.data
                for(let item of that.materialTable.columns){
                  if(item.key == 'lunch' || item.key == 'dinner' || item.key == 'night') {
                    item.options = []
                    for(let i=0; i<arr.length; i++) {
                      let displayName = arr[i].type + ' _ ' + arr[i].name
                      let depotInfo = {};
                      depotInfo.value = displayName
                      depotInfo.text = displayName
                      depotInfo.title = displayName
                      item.options.push(depotInfo)
                    }
                  }
                }
              }
            })
          }
          break;
        case "amount":
          amount = value-0
          let kucunAmountResult = row.kucunAmount - amount
          target.setValues([{rowKey: row.id, values: {kucunAmountResult: kucunAmountResult}}])
          target.recalcAllStatisticsColumns()
          break;
      }
    },
    //转为商品对象
    parseInfoToObj(mInfo) {
      return {
        barCode: mInfo.mBarCode,
        name: mInfo.name,
        standard: mInfo.standard,
        model: mInfo.model,
        color: mInfo.color,
        materialOther: mInfo.materialOther,
        unit: mInfo.commodityUnit,
        sku: mInfo.sku,
        amount: 1
      }
    },
    //使得型号、颜色、扩展信息、sku等为隐藏
    changeColumnHide() {
      this.changeFormTypes(this.materialTable.columns, 'model', 0)
      this.changeFormTypes(this.materialTable.columns, 'color', 0)
      this.changeFormTypes(this.materialTable.columns, 'materialOther', 0)
      this.changeFormTypes(this.materialTable.columns, 'sku', 0)
    },
    //使得sku、序列号、批号、到期日等为显示
    changeColumnShow(info) {
      if(info.model) {
        this.changeFormTypes(this.materialTable.columns, 'model', 1)
      }
      if(info.color) {
        this.changeFormTypes(this.materialTable.columns, 'color', 1)
      }
      if(info.materialOther) {
        this.changeFormTypes(this.materialTable.columns, 'materialOther', 1)
      }
      if(info.sku) {
        this.changeFormTypes(this.materialTable.columns, 'sku', 1)
      }
      if(info.enableSerialNumber === "1") {
        //如果开启出入库管理，并且类型等于采购、采购退货、销售、销售退货，则跳过
        if(this.inOutManageFlag && (this.prefixNo === 'CGRK' || this.prefixNo === 'CGTH' || this.prefixNo === 'XSCK' || this.prefixNo === 'XSTH')) {
          //跳过
        } else {
          this.changeFormTypes(this.materialTable.columns, 'snList', 1)
        }
      }
      if(info.enableBatchNumber === "1") {
        //如果开启出入库管理，并且类型等于采购、采购退货、销售、销售退货，则跳过
        if(this.inOutManageFlag && (this.prefixNo === 'CGRK' || this.prefixNo === 'CGTH' || this.prefixNo === 'XSCK' || this.prefixNo === 'XSTH')) {
          //跳过
        } else {
          this.changeFormTypes(this.materialTable.columns, 'batchNumber', 1)
          this.changeFormTypes(this.materialTable.columns, 'expirationDate', 1)
        }
      }
    },
    //删除一行或多行的时候触发
    onDeleted(ids, target) {
      target.recalcAllStatisticsColumns()
    }
  }
}